<template>
  <div class>
    <div class="card tr mb2">
      <el-tooltip content="显示字段筛选" placement="bottom" effect="light">
        <el-popover placement="bottom" width="200" trigger="click">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          >全选</el-checkbox>
          <el-checkbox-group v-model="showItemList" @change="handleCheckedChange">
            <el-checkbox v-for="(item,key) in allItemList" :key="key" :label="item">{{item.name}}</el-checkbox>
          </el-checkbox-group>
          <el-button slot="reference" icon="el-icon-menu" size="mini" type="primary" circle></el-button>
        </el-popover>
      </el-tooltip>
      <el-tooltip content="展开/收起表单" placement="bottom" effect="light">
        <el-button
          icon="el-icon-search"
          @click="formShow= !formShow"
          size="mini"
          type="primary"
          circle
        ></el-button>
      </el-tooltip>
      <el-tooltip content="下载当前表格数据" placement="bottom" effect="light">
        <el-button
          icon="el-icon-download"
          @click="handleDownload"
          size="mini"
          type="primary"
          circle
        ></el-button>
      </el-tooltip>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="showDialog">添加</el-button>
    </div>
    <div class="card form" v-show="formShow">
      <el-form inline :model="searchForm" size="mini" label-width="80px" ref="search">
        <my-form-item label="登陆账号" prop="username">
          <el-input v-model="searchForm.username" autocomplete="off" size="mini"></el-input>
        </my-form-item>
        <!-- <my-form-item label="组织机构" prop="organ">
          <el-cascader
            change-on-select
            :options="options"
            :props="cascaderProps"
            v-model="searchForm.organ"
          ></el-cascader>
        </my-form-item>-->

        <my-form-item>        
          <el-button size="mini" type="primary" @click="init">查询</el-button>
          <el-button size="mini" @click="resetForm('search')">重置</el-button>
        </my-form-item>
      </el-form>
    </div>

    <el-table ref="dragTable" row-key="id" :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="60px" fixed="left" align="center" label="序号"></el-table-column>
      <el-table-column v-for="(item,index) in allItemList" :key="index" :label="item.name" v-if="item.show">
        <template slot-scope="scope">
          <template v-if="!item.formatter">{{ scope.row[item.key] }}</template>
          <template v-else>
            <span v-text="item.formatter(scope.row, item)"></span>
          </template>
        </template>
      </el-table-column>

      <el-table-column width="250px" label="操作" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showEditDialog(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="success" @click="showQxDialog(scope.$index, scope.row)">权限</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">浏览</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <div class="card" style="text-align:right;">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="currentPage"
        :page-sizes="[ 10, 20,30, 40]"
        :page-size="pageSize"
        background
        layout="total, sizes, prev, pager, next"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog width="70%" title="角色权限" :visible.sync="dialogQsVisible">
      <select-role
        ref="selectRole"
        @selection="getSelectRoles"
        :defaultData="checkbox.checkedRoles"
      />
      <!-- <el-checkbox-group v-model="checkbox.checkedRoles">
        <el-checkbox
          v-for="item in checkbox.Roles"
          :label="item.id"
          :key="item.id"
        >{{item.roleName}}</el-checkbox>
      </el-checkbox-group>-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogQsVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="changeRole" size="mini">确 定</el-button>
      </div>
    </el-dialog>

    <add-form ref="addform" @addOver="init"></add-form>
    <edit-form ref="editform" :editForm="editForm" @editOver="init"></edit-form>
  </div>
</template>

<script>
import selectRole from "@/components/selectRole/selectRole";
import {
  addUserRole,
  getList,
  deleteItem,
  getRoleListByUserId
} from "./function";
import addForm from "./components/addForm";
import editForm from "./components/editForm";
import { getList as glbOptions } from "../organ/organ";
const defaultFormThead = [
  { key: "realName", name: "真实姓名",show:true},
  { key: "username", name: "登陆账号" ,show:true},
  { key: "telephone", name: "固定电话" ,show:true},
  { key: "createTime", name: "创建日期" ,show:true},
  {
    key: "userStatus",
    name: "启用状态",
    formatter: row => {
      if (row.userStatus == 1) {
        return "启用";
      } else {
        return "禁用";
      }
    },show:true
  }
];
export default {
  components: {
    addForm,
    editForm,
    selectRole
  },
  data() {
    return {
      key: 1,
      showItemList: defaultFormThead,
      allItemList: defaultFormThead,
      checkAll: true,
      isIndeterminate: false,
      formShow: false,
      createUserName: JSON.parse(sessionStorage.getItem("user")).username,
      qxUserId: "",
      checkbox: {
        checkedRoles: [],
        Roles: []
      },
      dialogQsVisible: false,
      formLabelWidth: "80px",
      tableData: [],
      editForm: {},
      searchForm: {
        username: "",
        usertype: "",
        organ: ""
      },
      options: [],
      cascaderProps: {
        value: "id",
        label: "organName",
        children: "children"
      },

      total: 0,
      pageSize: 10,
      currentPage: 1
    };
  },
  computed: {},
  watch: {
    showItemList(valArr) {
        for (let key in this.allItemList) {
          this.allItemList[key].show = false;
          for (let key1 in valArr) {
            if (this.allItemList[key].key == valArr[key1].key) {
              this.allItemList[key].show = true;
            }
          }
        }
      this.$nextTick(() => {
        this.$refs.dragTable.doLayout();
      });
    }
  },
  mounted() {
    this.init();
    this.getGlbOptions();
  },
  methods: {
    handleCheckedChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === defaultFormThead.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < defaultFormThead.length;
    },
    handleCheckAllChange(val) {
      this.showItemList = val ? defaultFormThead : [];
      this.isIndeterminate = false;
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = [
          "序号",
          "真实姓名",
          "登陆账号",
          "固定电话",
          "启用状态",
          "创建日期"
        ];
        const filterVal = [
          "id",
          "realName",
          "username",
          "telephone",
          "userStatus",
          "createTime"
        ];
        const data = this.formatJson(filterVal, this.tableData);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list-user"
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      let i = 0
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "id") {
            i++
            return i
          } else if(j=="userStatus"){
            return v[j]=="1"?"启用":"禁用"
          }else {
            return v[j];
          }
        })
      );
    },

    filter2(row, column, cellValue) {
      if (cellValue == 0) {
        return "不启用";
      }
      if (cellValue == 1) {
        return "启用";
      }
    },

    changeRole() {
      this.dialogQsVisible = false;

      let params = {
        userId: this.qxUserId,
        roleIds: this.checkbox.Roles
      };
      addUserRole(params).then(res => {
        if (res.retHead.code == "0000000") {
          this.$message.success(res.retHead.message);
        } else {
          this.$message.error(res.retHead.message);
        }
      });
    },
    showQxDialog(i, row) {
      this.checkbox.checkedRoles = [];
      this.qxUserId = row.id;
      this.dialogQsVisible = true;
      this.getRoleListByUserId();
    },
    getRoleListByUserId() {
      let params = {
        userId: this.qxUserId
      };
      getRoleListByUserId(params).then(res => {
        if (res.retHead.code == "0000000") {
          this.checkbox.checkedRoles = res.retBody;
          this.$refs.selectRole.init();
        }
      });
    },
    getSelectRoles(Roles) {
      this.checkbox.Roles = [];
      Roles.forEach(item => {
        this.checkbox.Roles.push(item.id);
      });
    },
    sizeChange(n) {
      this.pageSize = n;
      this.init();
    },
    currentChange(n) {
      this.currentPage = n;
      this.init();
    },
    getGlbOptions() {
      glbOptions().then(res => {
        console.log("ok");
        console.log(res.retBody);
        if (res.retHead.code == "0000000") {
          this.options = res.retBody;
        }
      });
    },
    init() {
      let params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        username: this.searchForm.username,
        organCode: this.searchForm.organ[this.searchForm.organ.length - 1] || ""

        // usertype: this.searchForm.usertype
      };
      getList(params).then(res => {
        console.log(res);
        if (res.retHead.code == "0000000") {
          this.tableData = res.retBody.list;
          this.total = res.retBody.total;
          this.currentPage = res.retBody.pageNum;
        }
      });
    },
    showDialog() {
      this.$refs.addform.dialogFormVisible = true;
    },
    showEditDialog(index, row) {
      this.$refs.editform.dialogEditVisible = true;
      this.editForm = JSON.parse(JSON.stringify(row));
      this.editForm.password = "";
      this.editForm.organCode = [row.organCode];
    },

    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteItem({ id: row.id }).then(res => {
            if (res.retHead.code == "0000000") {
              this.$message({
                message: "操作成功！",
                type: "success"
              });
              this.init();
            } else {
              this.$message({
                message: "操作失败！",
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  created() {}
};
</script>
<style lang='scss' scoped>
.btns {
  text-align: right;
}
</style>
